package project.register;



import org.json.JSONException;
import org.json.JSONObject;
import project.Dao.UserDao;
import project.Domain.User;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;

import static java.lang.System.out;

public class register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doGet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doPost");
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了login");
        try {
            processlogin(request, response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void processlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException {
        String role = request.getParameter("role");
        String email = request.getParameter("email");
        String mobile = request.getParameter("mobile");
        String name = request.getParameter("realName");
        String username = request.getParameter("userName");
        String password = request.getParameter("password");

        request.setCharacterEncoding("UTF-8");
        out.println("页面传递过来的数据:"+role+"\n"+email+"\n"+role+"\n"+mobile+"\n"+name+"\n"+username+"\n"+password);
        JSONObject json = new JSONObject();

        UserDao UserDao = new UserDao();
        //判断手机号是否注册过 true 注册过
        if(UserDao.hasMobile(mobile)){
            json.put("register_result", 0);
            json.put("register_fail_reason", "该手机号已被注册，请使用其他手机号进行注册！");
        }else if(UserDao.hasEmail(email)){
            json.put("register_result", 0);
            json.put("register_fail_reason", "该邮箱已被注册！");
        }else if (UserDao.login(username) != null){
            json.put("register_result", 0);
            json.put("register_fail_reason", "用户名已存在！");
        }else{
            User user = new User(name, email, mobile, role, username, password);
            if(user.getRole().equals("组长")) user.setLeaderID(1);
            else  if(user.getRole().equals("组员"))   user.setLeaderID(0);
            if(UserDao.Register(user)){
                json.put("register_result", 1);
            }else{
                json.put("register_result", 0);
                json.put("register_fail_reason", "服务器繁忙，请稍后重试！");
            }
        }
        out.println(json);
        //将响应消息返回页面
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();


    }
}
